package com.skivingcloud.admin.sys.service.impl;

import com.mybatisflex.core.query.QueryWrapper;
import com.mybatisflex.spring.service.impl.ServiceImpl;
import com.skivingcloud.admin.sys.entity.SysMenu;
import com.skivingcloud.admin.sys.entity.SysTenantMenu;
import com.skivingcloud.admin.sys.mapper.SysMenuMapper;
import com.skivingcloud.admin.sys.service.SysMenuService;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 *  服务层实现。
 *
 * @author skivingcloud
 * @since 2023-08-28
 */
@Service
public class SysMenuServiceImpl extends ServiceImpl<SysMenuMapper, SysMenu> implements SysMenuService {
    
    /**
     * 查询树形菜单
     *
     * @return 树形菜单
     */
    @Override
    public List<SysMenu> getMenuList(){
        QueryWrapper queryWrapper = QueryWrapper.create().orderBy("order_num");
        List<SysMenu> listAll = this.list(queryWrapper);
        return listAll.stream().filter(item -> {
            item.setChildren(listAll.stream().filter(e -> e.getParentId().equals(item.getId())).toList());
            return item.getParentId().equals("0");
        }).toList();
    }
    
    /**
     * 查询租户有权限的资源
     *
     * @param tenantId 租户ID
     * @return 树形菜单
     */
    @Override
    public List<SysMenu> getTenantMenuList(String tenantId){
        QueryWrapper queryWrapper = QueryWrapper.create().from(SysMenu.class).as("m").join(SysTenantMenu.class).as("tm").on(
                wrapper -> wrapper.where(SysMenu::getId).eq(SysTenantMenu::getMenuId)
        ).where(SysTenantMenu::getTenantId).eq(tenantId);
        List<SysMenu> listAll = this.mapper.selectListByQuery(queryWrapper);
        return listAll.stream().filter(item -> {
            item.setChildren(listAll.stream().filter(e -> e.getParentId().equals(item.getId())).toList());
            return item.getParentId().equals("0");
        }).toList();
    }
}
